package com.boot.controller;

import com.boot.annotation.RateLimit;
import com.boot.entity.Comment;
import com.boot.entity.Result;
import com.boot.exception.BusinessException;
import com.boot.service.ICommentService;
import com.boot.utils.SecurityUtils;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/api/comments")
@Slf4j
public class CommentController {

    @Resource
    private ICommentService commentService;

    /**
     * 发布评论
     */
    @PostMapping
    @RateLimit(limit = 5, windowSec = 60)
    public Result<String> postComment(@RequestBody CreateCommentRequest request) {
        try {
            SecurityUtils.requireCurrentUserId();

            if (request == null || request.getQuestionId() == null || request.getContent() == null) {
                return Result.fail("参数缺失");
            }

            String content = request.getContent().trim();
            if (content.isEmpty()) {
                return Result.fail("评论内容不能为空");
            }

            if (content.length() > 2000) {
                return Result.fail("评论内容过长（不超过2000字符）");
            }

            commentService.publishComment(request.getQuestionId(), content);
            return Result.success("评论已提交，等待审核");
        } catch (IllegalArgumentException | SecurityException | IllegalStateException | BusinessException e) {
            return Result.fail(e.getMessage());
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return Result.fail("系统错误");
        }
    }

    /**
     * 获取某问题下的所有已通过评论
     */
    @GetMapping("/question/{questionId}")
    @RateLimit(limit = 20, windowSec = 60)
    public Result<List<CommentDTO>> getComments(@PathVariable Long questionId) {
        try {
            SecurityUtils.requireCurrentUserId();

            List<Comment> comments = commentService.getApprovedCommentsByQuestionId(questionId);
            List<CommentDTO> dtos = comments.stream().map(this::convertToDTO).collect(Collectors.toList());
            return Result.success(dtos);
        } catch (IllegalArgumentException | SecurityException | IllegalStateException | BusinessException e) {
            return Result.fail(e.getMessage());
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return Result.fail("系统错误");
        }
    }

    // ========== DTO & 转换方法 ==========
    private CommentDTO convertToDTO(Comment comment) {
        CommentDTO dto = new CommentDTO();
        dto.setId(comment.getId());
        dto.setQuestionId(comment.getQuestionId());
        dto.setUserId(comment.getUserId());
        dto.setContent(comment.getContent());
        dto.setStatus(comment.getStatus());
        dto.setCreatedAt(comment.getCreatedAt());
        dto.setUsername(comment.getUsername());
        return dto;
    }

    // ========== Request/DTO ==========
    public static class CreateCommentRequest {
        private Long questionId;
        private String content;

        // getter/setter
        public Long getQuestionId() {
            return questionId;
        }

        public void setQuestionId(Long questionId) {
            this.questionId = questionId;
        }

        public String getContent() {
            return content;
        }

        public void setContent(String content) {
            this.content = content;
        }
    }

    @Data
    public static class CommentDTO {
        private Long id;
        private Long questionId;
        private Long userId;
        private String username; // 前端需要用户名
        private String content;
        private String status;
        private LocalDateTime createdAt;

        public String getCreatedAt() {
            return this.createdAt != null ? this.createdAt.toString() : "";
        }
    }

    /**
     * 修改评论
     */
    @PutMapping("/{commentId}")
    @RateLimit(limit = 3, windowSec = 60) // 每分钟最多修改3次
    public Result<String> updateComment(
            @PathVariable Long commentId,
            @RequestBody UpdateCommentRequest request) {
        try {
            Long userId = SecurityUtils.requireCurrentUserId();

            if (request == null || request.getContent() == null) {
                return Result.fail("评论内容不能为空");
            }

            String content = request.getContent().trim();
            if (content.isEmpty()) {
                return Result.fail("评论内容不能为空");
            }
            if (content.length() > 2000) {
                return Result.fail("评论内容过长（不超过2000字符）");
            }

            commentService.updateComment(commentId, userId, content);
            return Result.success("评论已更新，等待重新审核");
        } catch (IllegalArgumentException | SecurityException | IllegalStateException | BusinessException e) {
            return Result.fail(e.getMessage());
        } catch (Exception e) {
            log.error("更新评论失败", e);
            return Result.fail("系统错误");
        }
    }

    /**
     * 删除评论
     */
    @DeleteMapping("/{commentId}")
    @RateLimit(limit = 5, windowSec = 60)
    public Result<String> deleteComment(@PathVariable Long commentId) {
        try {
            Long userId = SecurityUtils.requireCurrentUserId();

            commentService.deleteComment(commentId, userId);
            return Result.success("评论已删除");
        } catch (IllegalArgumentException | SecurityException | IllegalStateException | BusinessException e) {
            return Result.fail(e.getMessage());
        } catch (Exception e) {
            log.error("删除评论失败", e);
            return Result.fail("系统错误");
        }
    }

    // ========== Request DTO ==========
    @Data
    public static class UpdateCommentRequest {
        private String content;
    }
}
